package com.cy.pj.goods;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository //次注解一般用于描述数据逻辑层的具体实现对象,此对象要交给spring管理
public class DeafaultGoodsDao  implements GoodsDao{
    @Autowired
    private DataSource dataSource;
    @Override
    public List<Map<String, Object>> findGoods()  {
        String sql="select * from tb_goods";
        Connection con=null;
        ResultSet rs=null;
        Statement stat=null;
        //获取连接
        try {
             con = dataSource.getConnection();
            //2.创建Statment对象,基于此对象发送sql语句
             stat = con.createStatement();
            //3.发送sqly语句
             rs = stat.executeQuery(sql);
            //4.处理结果集
            List<Map<String,Object>> list = new ArrayList<>();
            while (rs.next()) {
 //               HashMap<String, Object> map = new HashMap<>();
//                map.put("id", rs.getInt("id"));
//                map.put("name",rs.getString("name") );
//                map.put("remark",rs.getString("remark") );
//                map.put("createdTime", rs.getTimestamp("createdTime"));
                ResultSetMetaData me = rs.getMetaData();//获取原数据(就是表头)
                list.add(rowMap(me, rs));
            }
            return list;
        }catch (SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);//非检查异常 ,这样方法就不需要声明抛出了
        }
        //5.释放资源
        finally {
            if(rs!=null)try{rs.close();}catch (SQLException e){}
            if(stat!=null)try{stat.close();}catch (SQLException e){}
            if(con!=null)try{con.close();}catch (SQLException e){}

        }
    }
    public Map<String,Object> rowMap( ResultSetMetaData me,ResultSet rs) throws SQLException{
        HashMap<String, Object> map = new HashMap<>();
        int columnCount = me.getColumnCount();//获取列的数量
        for(int i=1;i<=columnCount;i++){
            //获取列别名,没有起别名的就是列别名
            String columnLabel = me.getColumnLabel(i);
            //将列的名字作为key,列的值作为value存储到map集合中
            map.put(columnLabel, rs.getObject(columnLabel));
        }
        return map;
    }
}
